<?php
/**
 * Created by PhpStorm.
 * User: chang
 * Date: 2019/5/2
 * Time: 15:02
 */

use App\Libs\PHPExcel\PHPExcel\PHPExcel_IOFactory;


/**
 * 生成可访问的image url
 * @param $image
 * @return string
 */
function build_image($image)
{
    if (empty($image)) {
        return "";
    }

    if (strtolower(substr($image, 0, 4)) == "http") {
        return $image;
    }
    return env('OSS_URL') . $image;
}


/**
 * 重写实现 http_build_query 提交实现(同名key)key=val1&key=val2
 * @param array $formData 数据数组
 * @param string $numericPrefix 数字索引时附加的Key前缀
 * @param string $argSeparator 参数分隔符(默认为&)
 * @param string $prefixKey Key 数组参数，实现同名方式调用接口
 * @return string
 */
function build_query($formData, $numericPrefix = '', $argSeparator = '&', $prefixKey = '')
{
    $str = '';
    if (empty($formData)) {
        return $str;
    }
    foreach ($formData as $key => $val) {
        if (!is_array($val)) {
            $str .= $argSeparator;
            if ($prefixKey === '') {
                if (is_int($key)) {
                    $str .= $numericPrefix;
                }
                $str .= urlencode($key) . '=' . urlencode($val);
            } else {
                $str .= urlencode($prefixKey) . '=' . urlencode($val);
            }
        } else {
            if ($prefixKey == '') {
                $prefixKey .= $key;
            }
            if (isset($val[0]) && is_array($val[0])) {
                $arr = array();
                $arr[$key] = $val[0];
                $str .= $argSeparator . http_build_query($arr);
            } else {
                $str .= $argSeparator . build_query($val, $numericPrefix, $argSeparator, $prefixKey);
            }
            $prefixKey = '';
        }
    }
    return substr($str, strlen($argSeparator));
}

/**
 * CURL请求 GET/POST
 * */
function curlRequest($url, $data = null, $body = false, $header = [], $timeout = 10)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);

    $header = empty($header) ? [] : $header;
    $header[] = "NOAES: 1";
    if (!empty($header)) {
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
    }

    if (!empty($data)) {
        $hadFile = false;
        if (is_array($data) && isset($data['media'])) {
            /**
             * 支持文件上传
             */
            if (class_exists('\CURLFile')) {
                curl_setopt($curl, CURLOPT_SAFE_UPLOAD, true);
                foreach ($data as $key => $value) {
                    if (isPostHasFile($value)) {
                        $data[$key] = new \CURLFile(realpath(ltrim($value, '@')));
                        $hadFile = true;
                    }
                }
            }
            /*elseif (defined('CURLOPT_SAFE_UPLOAD')) {
                if (isPostHasFile()) {
                    curl_setopt($curl, CURLOPT_SAFE_UPLOAD, false);
                    $hadFile = true;
                }
            }*/
        }
        $data = (!$hadFile && is_array($data)) ? http_build_query($data) : $data;

        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }

    if ($body) {
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_NOBODY, 0);// 只取body
    }

    curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    $httpInfo = curl_getinfo($curl);
    curl_close($curl);

    if ($body) {
        return [
            'body' => $output,
            'header' => $httpInfo,
        ];
    } else {
        return $output;
    }
}


function curl_request($action, $params, $contentType = 'urlencoded', $httpMethod = 'POST', $httpHeader = [])
{
    $ch = curl_init();
    if ($httpMethod == 'POST' && $contentType == 'urlencoded') {
        $httpHeader[] = 'Content-Type:application/x-www-form-urlencoded';
        curl_setopt($ch, CURLOPT_POST, $httpMethod);
        curl_setopt($ch, CURLOPT_POSTFIELDS, build_query($params));

    } elseif ($httpMethod == 'POST' && $contentType == 'json') {
        $httpHeader[] = 'Content-Type:application/json';
        curl_setopt($ch, CURLOPT_POST, $httpMethod);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
    } elseif ($httpMethod == 'GET' && $contentType == 'urlencoded') {
        $action .= strpos($action, '?') === false ? '?' : '&';
        $action .= build_query($params);
    } elseif ($httpMethod == 'PUT' && $contentType == "") {
        $httpHeader[] = 'Content-Type:';
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $httpMethod); //设置请求方式
        curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-HTTP-Method-Override: $httpMethod"));//设置HTTP头信息
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);//设置提交的字符串
    } elseif ($httpMethod == 'POST' && $contentType == 'plain') {
        $httpHeader[] = 'Content-Type:text/plain';
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
    }
    $httpHeader[] = "NOAES: 1";

    curl_setopt($ch, CURLOPT_URL, $action);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $httpHeader);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //处理http证书问题
    curl_setopt($ch, CURLOPT_HEADER, false);
    // 在尝试连接时等待的秒数
//        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT , 120);
    // 最大执行时间
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_DNS_USE_GLOBAL_CACHE, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $ret = curl_exec($ch);

    if (false === $ret) {
        $ret = curl_errno($ch);
    }
    curl_close($ch);
    return json_decode($ret, true);
}
function getKkaudioApiUrl()
{
    return config('kkaudio.kkaudio_api');
}
function getKkaudioActivityUrl()
{
    return config('kkaudio.kkaudio_activity');
}

function formatPrice(&$value, $key)
{
    if (is_numeric($value)) {
        $value = number_format($value, 2);
    }
}

function convertSize($size)
{
    $unit = array('byte', 'kb', 'mb', 'gb', 'tb', 'pb');
    return round($size / pow(1024, ($i = floor(log($size, 1024)))), 2) . ' ' . $unit[$i];
}

//写入日志 todo
function write_log($dirName, $request_desc = 'log', $requestData)
{
    $dirPath = storage_path() . '/apiLogs';
    if (!is_dir($dirPath)) {
        mkdir($dirPath, 0777, true);
    }
    if(is_array($requestData)){
        file_put_contents($dirPath . '/' . $dirName . '-' . date('Y-m-d') . '.log', '[' . date('Y-m-d H:i:s') . ']'  . ' ' . $request_desc  . ' ' . json_encode($requestData,JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
    }else{
        file_put_contents($dirPath . '/' . $dirName . '-' . date('Y-m-d') . '.log', '[' . date('Y-m-d H:i:s') . ']'  . ' ' . $request_desc  . ' ' . json_encode($requestData,JSON_UNESCAPED_UNICODE) . PHP_EOL, FILE_APPEND);
    }


}

function getAWeekTimeSlot($gdate = '', $weekStart = 1)
{
    if (!$gdate) {
        $gdate = date("Y-m-d");
    }
    $w = date("w", strtotime($gdate)); //取得一周的第几天,星期天开始0-6
    $dn = $w ? $w - $weekStart : 6; //要减去的天数
    $time[] = date("Y-m-d 00:00:00", strtotime("$gdate  - " . $dn . "  days "));
    $time[] = date("Y-m-d 23:59:59", strtotime("$time[0]  +6  days "));
    return $time; //返回开始和结束日期
}


function getAWeekTimeSlotByYmd($gdate = '', $weekStart = 1)
{
    if (!$gdate) {
        $gdate = date("Y-m-d");
    }
    $w = date("w", strtotime($gdate)); //取得一周的第几天,星期天开始0-6
    $dn = $w ? $w - $weekStart : 6; //要减去的天数
    $time[] = date("Y-m-d", strtotime("$gdate  - " . $dn . "  days "));
    $time[] = date("Y-m-d", strtotime("$time[0]  +6  days "));
    return $time; //返回开始和结束日期
}

//返回数组
function objToArray($document)
{
    return json_decode(json_encode($document), true);
}

//返回当前毫秒时间戳
function msectime() {
    list($msec, $sec) = explode(' ', microtime());
    $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
    return $msectime;
}

/**
 * cms后台远程调用api平台接口
 * @param string $urlSuffix
 * @param null $data
 * @return mixed
 */
function callKKAudioApi(string $urlSuffix, $data = null)
{
    return json_decode(curlRequest(getKkaudioApiUrl() . '/' . ltrim($urlSuffix, '/'), $data), true);
}

/**
 * 读取Excel文件内容
 * @param null $excel_file
 * @param null $start_row
 * @param null $end_row
 * @param null $is_del
 * @return array
 */
function excel_to_array($excel_file = null, $start_row = null, $end_row = null, $is_del = null)
{
    $test_data = [
        'excel_file' => $excel_file,
        'start_row' => $start_row,
        'end_row' => $end_row,
    ];

    if (!$excel_file) {
        $state = 0;
        $msg = 'Excel路径参数不全';
        $content = [];
    } else {

        //加载excel文件
        $filename = $excel_file;
        $objPHPExcelReader = PHPExcel_IOFactory::load($filename);

        $sheet = $objPHPExcelReader->getSheet(0); // 读取第一个工作表(编号从 0 开始，sheet)
        if (!$end_row) {
            $highestRow = $sheet->getHighestRow(); // 取得最大行数
        } else {
            $highestRow = $end_row;
        }
        $highestColumn = $sheet->getHighestColumn(); // 取得最大列数
        $highestColumn =  colToNum($highestColumn);
        if ($highestColumn > 100001) {
            $state = 0;
            $msg = '最大行数100001行，如有超过，请切割文件';
            $content = [];
        } else {
            if (!$start_row) { // 默认从第二行读
                $start_row = 2;
            }
            $res_arr = [];
            for ($row = $start_row; $row <= $highestRow; $row++) { // 一次读取一列
                $row_arr = [];
                for ($column = 0; $column<$highestColumn; $column++) {
                    $val = $sheet->getCellByColumnAndRow($column, $row)->getValue();
                    $row_arr[] = $val;
                }

                $res_arr[] = $row_arr;
            }
            $state = 1;
            $msg = 'Excel读取完成';
            $content = $res_arr;
            //读取完后删除文件；
            if (!empty($is_del)) {
                if (file_exists($filename)) {                            //判断文件存在
                    unlink($filename);     //删除
                }
            }
        }

    }

    return [
        'state' => $state,
        'msg' => $msg,
        'test_data' => $test_data,
        'content' => $content,
    ];
}

// 通过列名推导列排在第几个数字
function colToNum($col)
{
    $initAsciiNum = 64; // 第一个字母A的ASCII值
    $letterNum = 26; // 字母个数
    $num = 0;
    $len = strlen($col);
    for ($i = 0; $i < $len; $i++) {
        $c = $col[$len - $i - 1];
        $num += pow($letterNum, $i) * (ord($c) - $initAsciiNum);
    }
    return $num;
}


/**
 * 获取周的开始、结束 日期或时间戳
 * @param int $week 周数 （0=本周，>=1为上周、上上周...，<=-1为下周、下下周...）
 * @param int $timeType 时间类型（0=日期格式 1=时间戳格式）
 * @param string $format 格式
 * @return array
 */
function getWeekTimestamp($week = 0, $timeType = 0, $format = 'Y-m-d')
{
    $wn = date('w') ? date('w') : 7;    // 自然周一至周日，将周日0转换成7

    $startTime = date($format, mktime(0, 0, 0, date('m'), date('d') - $wn + 1 - ($week * 7), date('Y')));
    $endTime = date($format, mktime(23, 59, 59, date('m'), date('d') - $wn + 7 - ($week * 7), date('Y')));

    if ($timeType) {
        $startTime .= ' 00:00:00';
        $endTime .= ' 23:59:59';
        return [strtotime($startTime), strtotime($endTime)];
    }

    return [$startTime, $endTime];
}


/**
 * 获取URL路径
 */
if (!function_exists('getUrlPath')) {
    function getUrlPath($url){
        $parseArr = parse_url($url);
        if(!empty($parseArr['path'])){
            return $parseArr['path'];
        }
        return '';
    }
}

/**
 * curl返回值处理
 */
if (!function_exists('curlResultHandle')) {
    function curlResultHandle($res){
        $res['code'] = isset($res['code']) ? ($res['code']==0 ? 20000 : $res['code']) : 50000;
        if(!isset($res['msg'])) $res['msg'] = '失败';
        if(!isset($res['data'])) $res['data'] = [];

        return $res;
    }
}

/**
 * 导出Excel数据表格
 * @param  array    $dataList     要导出的数组格式的数据
 * @param  array    $headList     导出的Excel数据第一列表头
 * @param  string   $fileName     输出Excel表格文件名
 * @param  string   $exportUrl    直接输出到浏览器or输出到指定路径文件下
 * @return bool|false|string
 */
function generateCsv($dataList,$headList,$fileName,$exportUrl){
        set_time_limit(0);//防止超时
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'.$fileName.'.csv"');
        header('Cache-Control: max-age=0');
        $fp = fopen($exportUrl, 'a');

        //输出Excel列名信息
        foreach ($headList as $key => $value) {
            //CSV的Excel支持GBK编码，一定要转换，否则乱码
            $headList[$key] = mb_convert_encoding($value,"GBK","UTF-8");
        }

        //将数据通过fputcsv写到文件句柄
        fputcsv($fp, $headList);

        //计数器
        $num = 0;

        //每隔$limit行，刷新一下输出buffer，不要太大，也不要太小
        $limit = 100000;

        //逐行取出数据，不浪费内存
        $count = count($dataList);
        for ($i = 0; $i < $count; $i++) {

            $num++;

            //刷新一下输出buffer，防止由于数据过多造成问题
            if ($limit == $num) {
                ob_flush();
                flush();
                $num = 0;
            }

            $row = $dataList[$i];
            foreach ($row as $key => $value) {
                $row[$key] = mb_convert_encoding($value,"GBK","UTF-8");
            }
            fputcsv($fp, $row);
        }
    return $exportUrl;
}

//阿拉伯数字转中文数字
function numberToChinese(int $num)
{
    //节权位的位置
    $unit_section_pos = 0;
    $chn_str = '';
    //单个数字转换用的数组
    $chn_num_char = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
    //节权位转换用的数组
    $chn_unit_section = ["", "万", "亿", "万亿", "亿亿"];
    //节内权位换算的数组
    $chn_unit_char = ["", "十", "百", "千"];
    $need_zero = false;

    if ($num === 0) {
        return $chn_num_char[0];
    }

    //节内换算的闭包
    $section_to_chinese = function ($section) use ($chn_num_char, $chn_unit_char) {
        $chn_str = '';
        //节内的位置
        $unit_pos = 0;
        $zero = true;

        while ($section > 0) {
            $v = $section % 10;
            if ($v === 0) {
                if (!$zero) {
                    $zero = true;
                    $chn_str = $chn_num_char[$v] . $chn_str;
                }
            } else {
                $zero = false;
                $str_ins = $chn_num_char[$v];
                $str_ins .= $chn_unit_char[$unit_pos];
                $chn_str = $str_ins . $chn_str;
            }
            $unit_pos++;
            $section = floor($section / 10);
        }
        return $chn_str;
    };

    while ($num > 0) {
        $section = $num % 10000;
        if ($need_zero) {
            $chn_str = $chn_num_char[0] . $chn_str;
        }
        $str_ins = $section_to_chinese($section);
        $str_ins .= ($section !== 0) ? $chn_unit_section[$unit_section_pos] : $chn_unit_section[0];
        $chn_str = $str_ins . $chn_str;
        $need_zero = ($section < 1000) && ($section > 0);
        $num = floor($num / 10000);
        $unit_section_pos++;
    }

    $search = '一十';
    $replacement = '十';
    //处理含一十开头的（这个可根据需求处理）
    if (mb_substr($chn_str, 0, 2) === $search) {
        $position = strpos($chn_str, $search);
        $chn_str = substr_replace($chn_str, $replacement, $position, strlen($search));
    }

    return $chn_str;
}
